import requests
from bs4 import BeautifulSoup as bs
import datetime
import random
import sys
sys.path.append('.unit')
from unit.index import mkdirFile

def sole():
    for i in range(0, 10):
        nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # 生成当前时间
        randomNum = random.randint(0, 100)  # 生成的随机整数n，其中0<=n<=100
        if randomNum <= 10:
            randomNum = str(0) + str(randomNum)
        uniqueNum = str(nowTime) + str(randomNum)
        return uniqueNum


def main():
    # 请求的url
    # page = 0
    for i in range(172):
        page = i + 1
        if page == 1:
            url = 'http://pic.netbian.com/4kmeinv'
        else:
            url = 'http://pic.netbian.com/4kmeinv/index_%s.html'
            url = url % page
        # downloadImg(url)


def downloadImg(url):
    # 进行伪装
    headers = {
        "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/78.0.3904.108 Mobile Safari/537.36"
    }
    # 发起请求
    response = requests.get(url=url, headers=headers)
    # 手动设定响应数据的编码格式
    response.encoding = 'utf-8'
    page_text = response.text
    soup = bs(page_text, "html.parser")

    # 创建文件夹
    mkdirFile('./壁纸')

    span_list = soup.find_all("img")
    for s in span_list:
        if s.get('src'):
            img_data = requests.get(url='http://pic.netbian.com/' + s.get('src'), headers=headers).content
            img_name = sole() + '.jpg'
            img_path = '壁纸/' + img_name
            with open(img_path, 'wb') as fp:
                fp.write(img_data)
                print(img_name, '下载成功！！！')


main()
